<template>
  <BasicDrawer
    :headerStyle="{ padding: 0 }"
    v-bind="$attrs"
    :class="prefixCls"
    :closable="false"
    getContainer="body"
    width="100%"
    title="新增"
    :destroyOnClose="true"
    @register="registerDrawer"
  >
    <template #title>
      <div class="actions box-b-shadow flex items-center justify-end h-64px px-6">
        <div class="title">{{ isUpdate ? '编辑' : '新增' }} </div>
        <div class="title flex-1 flex justify-center">
          <HTabs
            v-model:active="tabIdx"
            class="px-6 tabs"
            :dataSource="tabCols"
            @change="changeTabs"
          />
        </div>

        <a-button type="default" @click="handleCancel">取消</a-button>
        <a-button type="primary" class="ml-4" @click="handleSumbit">保存</a-button>
      </div>
    </template>
    <div class="body">
      <div class="basic" v-show="tabIdx === 1">
        <div class="my-10">
          <BasicForm @register="registerForm" />
        </div>
      </div>
      <div class="model-design" v-show="tabIdx === 2">
        <ComplexDesign
          ref="designRef"
          :isShow="tabIdx === 2"
          :data="compositeDesignInfo"
          :update="isUpdate"
          :client="baseObj.client"
        />
      </div>
    </div>
  </BasicDrawer>
</template>

<script lang="ts" setup name="ModelConfig">
  import { ref } from 'vue';

  import { useDesign } from '/@/hooks/web/useDesign';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { HTabs } from '/@/components/HTabs';
  import ComplexDesign from './ComplexDesign.vue';
  // import { Steps } from 'ant-design-vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicForm, useForm } from '/@/components/Form/index';

  import { DesignInstance, tabCols, basicSchema } from './data';
  import {
    MODEL_TYPE,
    saveModelApi,
    updateModelApi,
    getModelInfoApi,
  } from '/@/api/config-center/model-design';

  const emit = defineEmits(['success', 'register']);
  const { prefixCls } = useDesign('ModelConfig');
  const { createMessage } = useMessage();

  const compositeDesignInfo = ref<Indexable>();
  const loading = ref(false);
  const tabIdx = ref(1);
  let modelId = '';
  const [
    registerForm,
    { validateFields: basicV, setFieldsValue: basicSets, updateSchema: basicUpdate },
  ] = useForm({
    labelWidth: 110,
    colon: false,
    baseColProps: { lg: 11, md: 23 },
    schemas: basicSchema,
    showActionButtonGroup: false,
  });
  let baseObj = ref<Indexable>({});
  const isUpdate = ref(false);
  const [registerDrawer, { closeDrawer }] = useDrawerInner(async (data) => {
    tabIdx.value = 1;
    modelId = data.record?.modelId;
    await init(modelId);

    isUpdate.value = !!data.isUpdate;
    basicUpdate([
      {
        field: 'modelCode',
        ifShow: isUpdate.value,
      },
      {
        field: 'client',
        dynamicDisabled: isUpdate.value,
      },
    ]);
  });

  async function init(modelId: string) {
    try {
      compositeDesignInfo.value = {};
      if (modelId) {
        loading.value = true;

        const data = await getModelInfoApi(modelId);
        basicSets(data);
        compositeDesignInfo.value = data.compositeDesignInfo;
        baseObj.value = data;
      }
    } catch (e: any) {
      createMessage.error(e.msg || JSON.stringify(e));
      throw e;
    } finally {
      loading.value = false;
    }
  }

  function handleCancel() {
    closeDrawer();
  }

  const designRef = ref<Nullable<DesignInstance>>(null);

  async function handleSumbit() {
    try {
      loading.value = true;
      const ret = await basicV();
      const compositeDesignInfo = await designRef.value?.getValues();

      if (!compositeDesignInfo || compositeDesignInfo.modelList.length <= 0) {
        return createMessage.warning('请添加模型');
      }
      const params = Object.assign(baseObj.value, ret, {
        classify: MODEL_TYPE.COMPLEX,
        compositeDesignInfo,
      });

      const ajaxFn = modelId ? updateModelApi : saveModelApi;
      await ajaxFn(params);
      loading.value = false;
      createMessage.success('操作成功', 0.8);
      emit('success');
      handleCancel();
    } catch (e: any) {
      createMessage.error(e.msg || JSON.stringify(e));
      throw e;
    }
  }

  async function changeTabs({ value }) {
    try {
      const ret = await basicV();

      baseObj.value = {
        ...baseObj.value,
        ...ret,
      };

      tabIdx.value = value;
    } catch (error) {
      tabIdx.value = 1;
    }
  }
</script>
<style lang="less" scoped>
  .actions {
    z-index: 2;
    width: 100%;
    background-color: @component-background;
  }

  .tabs {
    border-bottom: transparent !important;
  }

  .body {
    margin: 0 -16px;
    height: calc(100vh - 96px);

    .model-design {
      height: 100%;
    }
  }
</style>
